import { createAsyncThunk, createSlice, PayloadAction } from "@reduxjs/toolkit";
import axios from "axios";

export type UserStateType = {
  username: string;
  nickname: string;
};

const INIT_STATE: UserStateType = { username: "", nickname: "" };
// Redux Toolkit默认已经给我们继承了Thunk相关的功能：createAsyncThunk
export const fetchHomeMultidataAction: any = createAsyncThunk(
  "user/fetchHomeMultidataAction",
  async () => {
    const res = await axios.get("http://localhost:8000/api/user/infoss");
    return res.data;
  }
);

export const userSlice = createSlice({
  name: "user",
  initialState: INIT_STATE,
  reducers: {
    loginReducer: (
      state: UserStateType,
      action: PayloadAction<UserStateType>
    ) => {
      return action.payload; // 设置username nickname 到redux store
    },
    logoutReducer: () => INIT_STATE, //退出登录重置
  },
  //
  // 当createAsyncThunk创建出来的action被dispatch时，会存在三种状态：
  // pending：action被发出，但是还没有最终的结果；
  //  fulfilled：获取到最终的结果（有返回值的结果）；
  //  rejected：执行过程中有错误或者抛出了异常；
  // ts需要使用type 定义类型
  //文档参考 https://blog.csdn.net/m0_68324632/article/details/128846249
  extraReducers: {
    [fetchHomeMultidataAction.pending.type](state, action) {
      console.log("等待", state);
    },
    [fetchHomeMultidataAction.fulfilled.type](state, { payload }) {
      console.log("成功", payload);
    },
    [fetchHomeMultidataAction.rejected.type](state, action) {
      console.log("失败", state);
    },
  },
});
export const { loginReducer, logoutReducer } = userSlice.actions;

export default userSlice.reducer;
